import { userLogin } from "@/api/user";
import { useState, startTransition } from "react";
import { useNavigate } from "react-router-dom";
import "./style/index.scss";
import { Input, Button, message, Modal } from "antd";
import { UserOutlined, KeyOutlined } from "@ant-design/icons";
import { useDispatch } from 'react-redux'
import { setMenuList } from "@/store/modules/menu";

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [messageApi, msgs] = message.useMessage();
  const navigate = useNavigate();
  const dispatch = useDispatch()
  const [open, setOpen] = useState(false);
  const handleOk = () => {
    localStorage.setItem('isLogin',1)
    setOpen(false);
    // 包装异步更新，以避免组件挂起导致页面报错情况。
    startTransition(() => {
      navigate("/");
    });
  };
   function goLogin() {
    userLogin({
      username: username,
      password: password,
    }).then((res) => {
      if (res.code === 200) {
        localStorage.setItem('userInfo',JSON.stringify(res.data.user))
        localStorage.setItem('token',res.data.token)
        dispatch(setMenuList())
        setOpen(true);
      } else {
        messageApi.error(res.message);
      }
    });
  }
  return (
    <>
      {msgs}
      <div className="container">
        <div className="card">
          <h2>欢迎使用 react-admin</h2>
          <div>
            Username:
            <Input
              placeholder="请输入用户名"
              prefix={<UserOutlined />}
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
          </div>
          <div>
            Password:
            <Input.Password
              visibilityToggle={{
                visible: passwordVisible,
                onVisibleChange: setPasswordVisible,
              }}
              placeholder="请输入密码"
              prefix={<KeyOutlined />}
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>
          <Button type="primary" onClick={() => goLogin()}>
            登录
          </Button>
          <div className="goLR" onClick={() => navigate("/register")}>去注册</div>
          <Modal
            title="登录成功"
            open={open}
            onOk={handleOk}
            footer={[
              <Button key="submit" type="primary" onClick={handleOk}>
                确定
              </Button>,
            ]}
          >
            <div>即将跳转到首页</div>
          </Modal>
        </div>
      </div>
    </>
  );
};

export default Login;
